package com.horay.nettydemo.nio.buffer;

import lombok.extern.slf4j.Slf4j;

import javax.net.ServerSocketFactory;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.SocketAddress;
import java.net.SocketOption;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;
import java.util.Set;

/**
 * 分散、合并
 *
 * @author heyingcheng
 * @date 2019/11/24 0:06
 */
@Slf4j
public class ScatteringAndGatheringBuffer {

    public static void main(String[] args) {
        try {
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.socket().bind(new InetSocketAddress(7000));
            SocketChannel socketChannel = serverSocketChannel.accept();

            ByteBuffer[] byteBuffers = new ByteBuffer[2];
            byteBuffers[0] = ByteBuffer.allocate(5);
            byteBuffers[1] = ByteBuffer.allocate(3);

            long maxLength = 8;

            while(true) {
                long readLength = 0;
                
                while (readLength < maxLength) {
                    readLength += socketChannel.read(byteBuffers);
                    final long prl = readLength;
                    Arrays.stream(byteBuffers).map(byteBuffer -> String.format("readLength:[%s], position:[%s], limit:[%s]", prl, byteBuffer.position(), byteBuffer.limit())).forEach(log::info);
                }

                Arrays.stream(byteBuffers).forEach(byteBuffer -> byteBuffer.flip());

                long writeLength = 0;

                while (writeLength < maxLength) {
                    writeLength += socketChannel.write(byteBuffers);
                    final long prl = writeLength;
                    Arrays.stream(byteBuffers).map(byteBuffer -> String.format("writeLength:[%s], position:[%s], limit:[%s]", prl, byteBuffer.position(), byteBuffer.limit())).forEach(log::info);
                }

                log.info("maxLength:[{}], readLength:[{}], writeLength:[{}]", maxLength, readLength, writeLength);

                Arrays.stream(byteBuffers).forEach(byteBuffer -> byteBuffer.clear());
            }
        } catch (IOException e) {
            log.error("创建连接异常", e);
        }
    }

}
